package com.example.springboott1.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.example.springboott1.entity.AdminUser;
import com.example.springboott1.service.AdminUserService;
import com.example.springboott1.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private AdminUserService adminUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();


        // 获取请求头中的令牌
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)){
            return false;
        }
        System.out.println("请求头中的token是:"+token);
        JwtUtil.parseToken(token);
        String id;
        try {
            id= JWT.decode(token).getAudience().get(0);
        }catch (Exception e){
            return false;
        }
        AdminUser adminUser=adminUserService.getById(id);
        if (adminUser==null){
            return false;
        }else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
